package com.chen.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.chen.pojo.Role;
import com.chen.pojo.User;
import com.chen.service.role.RoleService;

@Controller
@RequestMapping(value="/role")
public class RoleController {
	@Resource
	private RoleService roleService;
	@RequestMapping(value="/rolelist")
	public String list(Model model){
		try {
			model.addAttribute("roleList", roleService.getRoleList());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "jsp/rolelist";
	}
	@RequestMapping(value="/query")
	@ResponseBody
	public Object queryRoleCode(@RequestParam String roleCode) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		Role role = new Role();
		role = roleService.queryRole(roleCode);
		if(role != null) {
			map.put("roleCode", "exist");
		} else {
			map.put("roleCode", "noexist");
		}
		return JSONArray.toJSONString(map);
	}
	
	@RequestMapping(value="/add")
	public String addView() {
		return "jsp/roleadd";
	}
	
	@RequestMapping(value="/addrole",method=RequestMethod.POST)
	public String addRole(Role role,HttpSession session) throws Exception{
		boolean flag = false;
		role.setCreatedBy((Integer)session.getAttribute("userId"));
		role.setCreationDate(new Date());
		flag = roleService.addRole(role);
		if(flag) {
			return "redirect:/role/rolelist";
		} else {
			return "jsp/roleadd";
		}
	}
	
	@RequestMapping(value="/viewrole/{roleid}")
	public String view(@PathVariable String roleid,Model model) throws Exception{
		Role role = new Role();
		role = roleService.getRoleById(roleid);
		if(role != null) {
			model.addAttribute("role", role);
			return "jsp/rolemodify";
		} else {
			return "redirect:/role/relelist";
		}
	}
	@RequestMapping(value="/modifyrole")
	public String modify(Role role,HttpSession session) throws Exception{
		boolean flag = false;
		role.setCreatedBy((Integer)session.getAttribute("userId"));
		role.setCreationDate(new Date());
		flag = roleService.updateRole(role);
		if(flag) {
			return "redirect:/role/rolelist";
		} else {
			return "jsp/rolemodify";
		}
	}
	@RequestMapping(value="/deleterole")
	@ResponseBody
	public Object delRole(String roleid) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		boolean flag = false;
		flag = roleService.deleteRole(roleid);
		if(flag) {
			map.put("delResult", "true");
		} else {
			map.put("delResult", "false");
		}
		return JSONArray.toJSONString(map);
	}
}
